package com.ca.ridersclubapplication.request;

import android.app.Activity;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.data.entity.LongEntity;
import com.ca.ridersclubapplication.data.entity.StringEntity;
import com.ca.ridersclubapplication.data.entity.Token;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.util.MD5Utils;

import java.io.File;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.POST;
import retrofit2.http.Query;

public class FileRequester {

    public static final String URL = "file/";
    public static final String HEADER_BY_EMAIL_BASE_URL = Config.BASE_URL + URL + "header/getByEmail?email=";
    public static final String HEADER_BY_ID_BASE_URL = Config.BASE_URL + URL + "header/getById?id=";
    public static final String CLUB_IMAGE_1_1_BASE_URL = Config.BASE_URL + URL + "club/image?size=1-1&clubId=";
    public static final String CLUB_IMAGE_16_9_BASE_URL = Config.BASE_URL + URL + "club/image?size=16-9&clubId=";
    public static final String CLASSIFY_IMAGE_BASE_URL = Config.BASE_URL + URL + "classify/image?classifyId=";
    public static final String PAPER_IMAGE_BASE_URL = Config.BASE_URL + URL + "paper/image/get";

    public static final FileAPI api;

    static {
        api = new Retrofit.Builder()
                .baseUrl(Config.BASE_URL + URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(FileAPI.class);
    }

    public interface FileAPI {

        @POST("header/upload")
        Call<Result<String>> uploadHeaderImage(
                @Body RequestBody body,
                @Header("Authorization") String token,
                @Header("arg0") String hid,
                @Header("arg1") String email);

        @POST("paper/image/upload")
        Call<Result<String>> uploadPaperImage(
                @Body RequestBody body,
                @Header("Authorization") String token,
                @Header("arg0") String hid,
                @Header("arg1") String email);

        @GET("header/md5")
        Call<Result<String>> getHeaderMD5(@Query("accountId") Long accountId);
    }

    public static void uploadHeaderImage(Activity activity, String path, AfterExecutor<String> executor) {
        //  获取图片，创建请求体
        try {
            File file = new File(path);
            MultipartBody.Builder builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("header", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
            MultipartBody body = builder.build();
            //  发起请求
            Token token = DataHandler.getToken(activity);
            api.uploadHeaderImage(body, token.getToken(), String.valueOf(token.getId()), token.getEmail())
                    .enqueue(new Callback<Result<String>>() {
                        @Override
                        public void onResponse(@NonNull Call<Result<String>> call, @NonNull Response<Result<String>> response) {
                            Result<String> b = response.body();
                            if (b == null) {
                                Toast.makeText(activity, "上传失败", Toast.LENGTH_SHORT).show();
                                Log.e("Upload Failed", "body is null");
                                return;
                            }

                            if (!b.isSuccess()) {
                                Toast.makeText(activity, "上传失败", Toast.LENGTH_SHORT).show();
                                Log.e("Upload Failed", b.getMessage());
                                return;
                            }

                            Toast.makeText(activity, "上传成功", Toast.LENGTH_SHORT).show();

                            //  更新数据处理器（DataHandler）中对应的MD5
                            String md5 = MD5Utils.getMD5(path);
                            DataHandler.putData(new StringEntity("HeaderMD5:" + token.getId(), md5));

                            //  执行后续任务
                            if (executor != null) {
                                executor.execute(b);
                            }
                        }

                        @Override
                        public void onFailure(@NonNull Call<Result<String>> call, @NonNull Throwable t) {
                            Toast.makeText(activity, "上传失败", Toast.LENGTH_SHORT).show();
                            Log.e("UploadHeader Failed", t.getMessage());
                        }
                    });
        }
        catch (Exception e) {
            Log.e("UploadHeader Failed", e.getMessage());
            Toast.makeText(activity, "上传失败", Toast.LENGTH_SHORT).show();
        }
    }

    public static void getHeaderMD5(Activity activity, Long accountId, AfterExecutor<String> executor) {
        api.getHeaderMD5(accountId)
                .enqueue(new APICallback<String>(activity, executor) {
                    @Override
                    public void onResponse(@NonNull Call<Result<String>> call, @NonNull Response<Result<String>> response) {
                        super.onResponse(call, response);
                        if (isSuccess()) {
                            DataHandler.putData(new StringEntity("HeaderMD5:" + accountId, getData()));
                        }
                    }
                });
    }

    public static void uploadPaperImages(Activity activity, String key, List<String> pathList, AfterExecutor<String> executor) {

        for (String path : pathList) {
            File file = new File(path);
            MultipartBody.Builder builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("paperImage", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
            MultipartBody body = builder.build();

            Token token = DataHandler.getToken(activity);
            api.uploadPaperImage(body, token.getToken(), String.valueOf(token.getId()), token.getEmail())
                    .enqueue(new APICallback<String>(activity, executor) {
                        @Override
                        public void onResponse(@NonNull Call<Result<String>> call, @NonNull Response<Result<String>> response) {
                            super.onResponse(call, response);
                            if (isSuccess()) {
                                //  请求成功，将其存入数据处理器中
                                DataHandler.appendStringData(key, getData());
                                DataHandler.incData(new LongEntity("UploadImageSize", 1L));
                                Log.e("UploadImage", "appendData: " + key + ", " + getData());
                                Log.e("UploadImage", "incData: UploadImageSize, " + 1);
                            }
                        }
                    });
        }
    }
}
